package com.dmall.graph.bfs;

import com.dmall.graph.Graph;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author: xiao1.wang
 * @date: 2022/6/19 16:35
 */
public class BipartitionDetection1 {
    private Graph G;
    private final int[] colors;
    private boolean isBipartite = true;

    public BipartitionDetection1(Graph G) {
        this.G = G;
        this.colors = new int[G.V()];
        for (int i = 0; i < G.V(); i++) {
            if (colors[i] == 0) {
                if (!bfs(i)) {
                    isBipartite = false;
                    break;
                }
            }
        }
    }

    private boolean bfs(int v) {
        colors[v] = 1;
        Queue<Integer> queue = new LinkedList<>();
        queue.add(v);
        while (!queue.isEmpty()) {
            Integer cur = queue.remove();
            for (Integer w : G.adj(cur)) {
                if (colors[w] == 0) {
                    colors[w] = 3 - colors[cur];
                    queue.add(w);
                } else {
                    if (colors[w] == colors[cur]) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    public boolean isBipartite(){
        return isBipartite;
    }

    public static void main(String[] args) {
        String filename = BipartitionDetection1.class.getClassLoader().getResource("g.txt").getPath();
        Graph g = new Graph(filename);
        BipartitionDetection1 biPartitionDetection = new BipartitionDetection1(g);
        System.out.println(biPartitionDetection.isBipartite());

        String filename2 = BipartitionDetection1.class.getClassLoader().getResource("g3.txt").getPath();
        Graph g2 = new Graph(filename2);
        BipartitionDetection1 biPartitionDetection2 = new BipartitionDetection1(g2);
        System.out.println(biPartitionDetection2.isBipartite());
    }
}
